
import datetime

from sqlalchemy import Column, Integer, String, DateTime, UniqueConstraint
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine


Base = declarative_base()

class TestSuite(Base):
    __tablename__ = 'TestSuite'
    __table_args__ = ( UniqueConstraint('place','roundno' ), )

    id = Column(Integer, primary_key = True )
    place = Column(String)
    roundno = Column(String)
    starttime = Column(DateTime, default=datetime.datetime.now)
    endtime = Column(DateTime )
    status = Column(String)
    #unique_suite = UniqueConstraint(place, roundno)

    def __init__(self, place, roundno):
        self.place = place
        self.roundno = roundno
    def __repr__(self):
        return '<TestSuite: "{}","{}","{}",>'.format(self.id, self.place, self.roundno )

class PageTestDetail(Base):
    __tablename__ = 'PageTestDetail'
    __table_args__ = ( UniqueConstraint('suite_id','url' ), )
    id = Column(Integer, primary_key = True )
    suite_id = Column(Integer)
    url = Column(String)
    testtime = Column(String)
    loadtime = Column(Integer)
    sent = Column(Integer)
    received = Column(Integer)
    rescount = Column(Integer)
    errorcount = Column(Integer)
    
    def __init__(self, suite_id):
        self.suite_id = suite_id

    def __repr__(self):
        return '<PageTestDetail: "{}","{}","{}",>'.format(self.id, self.suite_id, self.url )
    
def getSession():
    engine = create_engine('sqlite:///qxtest.db', echo=True)
    Session = sessionmaker(bind=engine)
    return Session()


def TestStart( data ):
    session = getSession()
    result = session.query(TestSuite)\
            .filter(TestSuite.roundno == data['roundno'] )\
            .filter(TestSuite.place == data['place']).all()
    
    if len(result) == 1 :
        pts = result[0]
        pts.starttime = datetime.datetime.now()
        pts.status = '0'
        session.merge(pts)
    elif len(result) == 0:
        pts = TestSuite(data['place'], data['roundno'])
        pts.status = '0' 
        session.add(pts)
    else:
        print "Error Multi rows return."
    
    session.commit()


def TestEnd( data ):
    session = getSession()
    result = session.query(TestSuite)\
            .filter(TestSuite.roundno == data['roundno'] )\
            .filter(TestSuite.place == data['place']).all()
    
    if len(result) == 1 :
        pts = result[0]
        pts.endtime = datetime.datetime.now()
        pts.status = '1'
        session.merge(pts)
    else:
        print "Error Multi rows return."
    
    session.commit()

def PageTest( data ):
    session = getSession()
    try:
        ts = session.query(TestSuite)\
                .filter(TestSuite.roundno == data['roundno'] )\
                .filter(TestSuite.place == data['place']).one()
        
        result = session.query(PageTestDetail)\
                .filter(PageTestDetail.suite_id == ts.id )\
                .filter(PageTestDetail.url == data['url']).all()

        if len(result) == 1:
            pt = result[0]
            pt.url = data['url']
            pt.testtime = data['testtime']
            pt.loadtime = data['loadtime']
            pt.sent = data['sent']
            pt.received = data['received']
            pt.rescount = data['rescount']
            pt.errorcount = data['errorcount']
            session.merge(pt)
        else:
            pt = PageTestDetail( ts.id )
            pt.url = data['url']
            pt.testtime = data['testtime']
            pt.loadtime = data['loadtime']
            pt.sent = data['sent']
            pt.received = data['received']
            pt.rescount = data['rescount']
            pt.errorcount = data['errorcount']
            session.add(pt)
            
        session.commit()
    except NoResultFound, e:
        print e
        print "Error : TestSuite not Exist."


